package com.sjzd.net;

import com.sjzd.exception.LoadException;

import java.io.*;
import java.util.Properties;

public class ConnectConfigParser {
    private static final String PATH = "connectConfig.properties";
    private String serverIP = null;
    private Integer serverTCPPort = null;
    private Integer serverUDPPort = null;
    private Integer clientUDPPort = null;

    public ConnectConfigParser() {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getPATH() {
        return PATH;
    }

    public String getServerIP() {
        return serverIP;
    }

    public void setServerIP(String serverIP) {
        this.serverIP = serverIP;
    }

    public Integer getServerTCPPort() {
        return serverTCPPort;
    }

    public void setServerTCPPort(Integer serverTCPPort) {
        this.serverTCPPort = serverTCPPort;
    }

    public Integer getServerUDPPort() {
        return serverUDPPort;
    }

    public void setServerUDPPort(Integer serverUDPPort) {
        this.serverUDPPort = serverUDPPort;
    }

    public Integer getClientUDPPort() {
        return clientUDPPort;
    }

    public void setClientUDPPort(Integer clientUDPPort) {
        this.clientUDPPort = clientUDPPort;
    }

    public void init() throws IOException {
        Properties p = new Properties();
        InputStream inStream = ConnectConfigParser.class.getClassLoader().getResourceAsStream(PATH);
        if (null == inStream) {
            throw new LoadException("读取不到配置文件");
        }
        p.load(inStream);
        serverIP = p.getProperty("serverIP");
        serverTCPPort = Integer.parseInt(p.getProperty("serverTCPPort"));
        serverUDPPort = Integer.parseInt(p.getProperty("serverUDPPort"));
        clientUDPPort = Integer.parseInt(p.getProperty("clientUDPPort"));
    }

    public void update(String propertyName, String newPropertyValue) throws IOException {
        FileOutputStream fos = new FileOutputStream(PATH);
        Properties p = new Properties();
        InputStream inStream = ConnectConfigParser.class.getClassLoader().getResourceAsStream(PATH);
        if (null == inStream) {
            throw new LoadException("读取不到配置文件");
        }
        p.load(inStream);
        p.setProperty(propertyName, newPropertyValue);
        p.store(fos, null);
    }
}
